package org.ysu.shoeShopping.controller;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.ysu.shoeShopping.dto.CartItem;
import org.ysu.shoeShopping.dto.CartRequest;
import org.ysu.shoeShopping.entity.Cart;
import org.ysu.shoeShopping.service.CartService;
import org.ysu.shoeShopping.tools.Result;

import javax.annotation.Resource;
import java.util.List;

/**
 * 购物车(Cart)表控制层
 *
 * @author makejava
 * @since 2025-09-21 17:10:52
 */
@RestController
@RequestMapping("cart")
@CrossOrigin(origins = "*")
public class CartController {

    /**
     * 服务对象
     */
    @Resource
    private CartService cartService;

    /**
     * 分页查询
     *
     * @param cart 筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Cart>> queryByPage(Cart cart, PageRequest pageRequest) {
        return ResponseEntity.ok(this.cartService.queryByPage(cart, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Cart> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.cartService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param cart 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Cart> add(@RequestBody Cart cart) {
        return ResponseEntity.ok(this.cartService.insert(cart));
    }

    /**
     * 编辑数据
     *
     * @param cart 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Cart> edit(@RequestBody Cart cart) {
        return ResponseEntity.ok(this.cartService.update(cart));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.cartService.deleteById(id));
    }

    /**
     * 根据用户的uid查找购物车数据
     *
     * @param uid 用户ID
     * @return 购物车商品列表
     */
    @GetMapping("/find/{uid}")
    public Result<List<CartItem>> findCartMessage(@PathVariable Integer uid) {
        try {
            List<CartItem> cartItems = cartService.getCartItems(uid);
            return Result.success(cartItems);
        } catch (Exception e) {
            return Result.fail("500", "查询购物车失败: " + e.getMessage());
        }
    }

    /**
     * 加入购物车 - JSON方式
     * 接收包含鞋子id、尺码、数量、uid的购物车信息
     *
     * @param cartRequest 购物车信息
     * @return 添加结果
     */
    @PostMapping(value = "/add", consumes = "application/json")
    public Result<String> addToCartMessage(@RequestBody CartRequest cartRequest) {
        try {
            // 验证必需的参数
            if (cartRequest.getUid() == null || cartRequest.getSid() == null ||
                cartRequest.getSizeid() == null) {
                return Result.fail("400", "缺少必需的参数");
            }

            // 如果数量为空，默认为1
            Integer quantity = cartRequest.getQuantity() != null ? cartRequest.getQuantity() : 1;

            boolean success = cartService.addToCart(cartRequest.getUid(), cartRequest.getSid(),
                                                  cartRequest.getSizeid(), quantity);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.fail("500", "添加失败");
            }
        } catch (Exception e) {
            return Result.fail("500", "添加失败: " + e.getMessage());
        }
    }

    /**
     * 加入购物车 - 表单方式
     * 接收表单参数
     *
     * @param uid 用户ID
     * @param sid 商品ID
     * @param sizeid 尺码ID
     * @param quantity 数量（可选，默认1）
     * @return 添加结果
     */
    @PostMapping(value = "/add", consumes = "application/x-www-form-urlencoded")
    public Result<String> addToCartForm(@RequestParam Integer uid,
                                       @RequestParam Integer sid,
                                       @RequestParam Integer sizeid,
                                       @RequestParam(required = false, defaultValue = "1") Integer quantity) {
        try {
            // 验证必需的参数
            if (uid == null || sid == null || sizeid == null) {
                return Result.fail("400", "缺少必需的参数");
            }

            boolean success = cartService.addToCart(uid, sid, sizeid, quantity);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.fail("500", "添加失败");
            }
        } catch (Exception e) {
            return Result.fail("500", "添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     *
     * @param cartId 购物车ID
     * @param quantity 新数量
     * @return 更新结果
     */
    @PutMapping("/update/{cartId}")
    public Result<String> updateCartQuantity(@PathVariable Integer cartId,
                                           @RequestParam Integer quantity) {
        try {
            boolean success = cartService.updateCartQuantity(cartId, quantity);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.fail("500", "更新失败");
            }
        } catch (Exception e) {
            return Result.fail("500", "更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除购物车中的商品
     *
     * @param id 购物车记录ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteCartMessage(@PathVariable Integer id) {
        try {
            boolean success = cartService.removeFromCart(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.fail("404", "未找到该商品");
            }
        } catch (Exception e) {
            return Result.fail("500", "删除失败: " + e.getMessage());
        }
    }

    /**
     * 清空用户购物车
     *
     * @param userId 用户ID
     * @return 清空结果
     */
    @DeleteMapping("/clear/{userId}")
    public Result<String> clearCart(@PathVariable Integer userId) {
        try {
            boolean success = cartService.clearCart(userId);
            if (success) {
                return Result.success("清空成功");
            } else {
                return Result.fail("500", "清空失败");
            }
        } catch (Exception e) {
            return Result.fail("500", "清空失败: " + e.getMessage());
        }
    }
}